package com.yhsoft.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhsoft.common.service.Po.TokenUser;
import com.yhsoft.common.service.TokenService;
import com.yhsoft.sys.controller.Response.NoticeListOutVo;
import com.yhsoft.sys.controller.request.AddNoticeInVo;
import com.yhsoft.sys.controller.request.NoticeListInVo;
import com.yhsoft.sys.entity.Notice;
import com.yhsoft.sys.mapper.NoticeMapper;
import com.yhsoft.sys.service.INoticeService;
import com.yhsoft.sys.service.INoticeUsersService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * <p>
 * 公告信息表 服务实现类
 * </p>
 *
 * @author yyyyyyyh
 * @since 2023-11-20
 */
@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements INoticeService {

    @Resource
    private INoticeUsersService inoticeUsersService;

    @Override
    public String add(AddNoticeInVo inVo) {
        Notice notice = new Notice();
        notice.setTitle(inVo.getTitle());
        notice.setType(inVo.getType());
        notice.setNoticeRange(inVo.getRange());
        notice.setContent(inVo.getContent());
        notice.setDeleted(0);
        this.getBaseMapper().insert(notice);
        inoticeUsersService.add(notice.getId(), inVo.getType(), inVo.getRange());
        return "success";
    }

    @Override
    public IPage<NoticeListOutVo> getList(NoticeListInVo inVo, Long pageNo, Long pageSize) {
        TokenUser user = TokenService.getUserBytoken();

        LambdaQueryWrapper<Notice> wrapper = new LambdaQueryWrapper<>();
        if (!"sys".equals(user.getSysType())) {
            wrapper.inSql(Notice::getId, "select notice_id as id from baic_notice_users where user_id = '" + user.getId() + "'");
        }

        wrapper.ge(inVo.getStartTime() != null, Notice::getCreateTime, inVo.getStartTime());
        if (inVo.getEndTime() != null) {
            wrapper.le(Notice::getCreateTime, LocalDateTime.of(inVo.getEndTime(), LocalTime.MAX));
        }

        Page<Notice> page = new Page<>(pageNo, pageSize);
        IPage<Notice> iPage = baseMapper.selectPage(page, wrapper);

        IPage<NoticeListOutVo> convert = iPage.convert(notice -> {
            NoticeListOutVo form = new NoticeListOutVo();
            BeanUtils.copyProperties(notice, form);
            return form;
        });

        return convert;
    }
}
